<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['teaching:design:add']"
              >新增</el-button>
            </el-col>
      <!--      <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['teaching:design:edit']"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['teaching:design:remove']"
              >删除</el-button>
            </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="dict.type.sys_stage" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="value" />
      <el-table-column label="阶段" align="center" prop="label" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['teaching:design:edit']"
          >设计课程</el-button>
          <!--          <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDelete(scope.row)"
                      v-hasPermi="['teaching:design:remove']"
                    >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :page-sizes="[200,500]"
      :page-size="200"
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程设计对话框 -->
    <el-dialog :title="title" fullscreen :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="阶段" prop="stage">
          <el-select v-model="form.stage" placeholder="请选择阶段" :disabled="title=='修改课程设计'">
            <el-option
              v-for="dict in dict.type.sys_stage"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程天数">
          <el-input v-model="this.courseDesignList.length" :disabled="courseDesignList.length>0"/>
        </el-form-item>

        <el-divider></el-divider>
        <el-form-item :label="'第'+(i+1)+'天'" v-for="(cd,i) in courseDesignList" :key="i" ref="itemRefs" :id="(i)" class="dragClass">
          <el-col span="14" >
            <el-input v-model="cd.courseContent" :ref="'input-'+i"/>
          </el-col>
          <el-col span="2">
          </el-col>
          <el-col span="10">
            <el-button class="drag-btn" icon="el-icon-sort" :ref="'btn-'+i" :value="'btn-'+i" :draggable="true"></el-button>
            <el-button  icon="el-icon-circle-plus-outline" @click="addCourseDesign(i)" ></el-button>
            <el-button  icon="el-icon-remove-outline" @click="subCourseDesign(i)"></el-button>
            <el-button  icon="el-icon-paperclip" @click="handleRelatedInterview(cd)" v-if="cd.id">自动关联面试题</el-button>
          </el-col>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item >
          <el-col span="2">
            <el-input
              type="text"
              placeholder="天数"
              v-model="num"
              maxlength="2"
              show-word-limit
            ></el-input>
          </el-col>
          <el-col span="6">
            <el-button type="primary" icon="el-icon-finished" @click="batchAddCourseDesign">批量新增</el-button>
            <el-button type="danger" @click="resetCourseDesign" plain>还原</el-button>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer
      size="60%"
      title="关联面试题"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose" @click="">
      <el-form :label-position="labelPosition" @submit.native.prevent label-width="10px" :model="formLabelAlign">
        <el-form-item label="">
          <el-checkbox-group v-model="selectedKeyWords" @change="handleSelectedKeywords">
            <el-checkbox :label="keyword" v-for="keyword in keywords"></el-checkbox>
          </el-checkbox-group>
          <el-input v-model="newKeyWord" style="width: 50%" placeholder="关键字" @keyup.enter.native="handleAddKeyWord"></el-input>
          <el-button
            size="medium"
            type="primary"
            style="width:10%;"
            @click="handleAddKeyWord"
          >
            <span >新增</span>
          </el-button>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="">
          <el-table
            ref="multipleTable"
            :data="relatedInterviewList"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleRelatedInterviewSelectionChange">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              label="问题"
            >
              <template slot-scope="scope">{{ scope.row.question }}</template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRelatedInteview">保存</el-button>
        </el-form-item>
      </el-form>

    </el-drawer>
  </div>
</template>

<script>
import { saveRelatedInterview,listCourse_design, getCourse_design, delCourse_design, updateCourse_design } from "@/api/teaching/course_design";
import { queryRelatedInterview ,queryRelatedInterviewByKeywords} from "@/api/teaching/interview";
// 引入
import draggable from "vuedraggable";
export default {
  name: "Course_design",
  dicts: ['sys_stage'],
  data() {
    return {
      newKeyWord: "",
      selectedKeyWords:[],
      keywords:[],
      selectedCourseDesign:null,
      selectedInterviewIdList:[],
      relatedInterviewList:[],
      drawer: false,
      direction: 'rtl',
      num:1,
      bakCourseDesignList:[],
      courseDesignList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程设计表格数据
      designList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        courseContent: null,
        courseId: null,
        day: null,
        stage: null,
        teacher: null,
        remarks: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        courseContent: [
          { required: true, message: "课程内容不能为空", trigger: "blur" }
        ],
        courseId: [
          { required: true, message: "课程ID不能为空", trigger: "blur" }
        ],
        day: [
          { required: true, message: "第几天不能为空", trigger: "blur" }
        ],
        stage: [
          { required: true, message: "阶段不能为空", trigger: "change" }
        ],
        teacher: [
          { required: true, message: "授课老师不能为空", trigger: "blur" }
        ],
        remarks: [
          { required: true, message: "备注信息不能为空", trigger: "blur" }
        ]
      },
      dragItem:null
    };
  },
  created() {
    this.getList();
  },
  mounted() {
  },
  methods: {
    //新增关键字
    handleAddKeyWord(){
      if(!this.newKeyWord){
        return;
      }
      if(this.keywords.includes(this.newKeyWord)){
        return;
      }

      this.keywords.push(this.newKeyWord);
      this.handleSelectedKeywords();
    },
    //根据选中关键字重新获取面试题
    handleSelectedKeywords(){
      queryRelatedInterviewByKeywords(this.selectedKeyWords).then(response => {
        this.relatedInterviewList = response.data;
      });
    },
    handleRelatedInteview(){
      if (!this.selectedInterviewIdList && this.selectedInterviewIdList.length == 1) {
        this.$modal.msgError("至少选中一个面试题");
        return;
      }
      if (!this.selectedCourseDesign.id) {
        this.$modal.msgError("请先保存课程设计后再试");
        return;
      }
      saveRelatedInterview(this.selectedCourseDesign.id,this.selectedInterviewIdList).then(response => {
        this.$modal.msgSuccess("关联面试题成功");
        this.drawer = false;
      });
    },
    handleRelatedInterviewSelectionChange(selectedInterviewList) {
      this.selectedInterviewIdList = selectedInterviewList.map((interview)=>interview.id);
    },
    //查询关联面试题
    handleRelatedInterview(courseDesign) {
      this.keywords = [],
      this.selectedKeyWords = [],
      this.selectedCourseDesign = courseDesign;
      this.drawer=true;
      this.relatedInterviewList = [],
        this.selectedInterviewIdList = [],
        queryRelatedInterview(courseDesign.id,courseDesign.courseContent).then(response => {
          this.relatedInterviewList = response.data.highInterviewList;
          this.keywords = response.data.keywords;
          this.selectedKeyWords = response.data.keywords;
          this.relatedInterviewIdList = response.data.relatedInterviewIdList;
          //等渲染出来后，再设置为选中
          this.$nextTick(()=>{
            if (this.relatedInterviewIdList&&this.relatedInterviewIdList.length>0) {
              for (let i = 0; i < this.relatedInterviewIdList.length; i++) {
                let id = this.relatedInterviewIdList[i];
                let index = this.relatedInterviewList.findIndex((ri)=>ri.id == id);
                if (index>=0) {
                  this.$refs.multipleTable.toggleRowSelection(this.relatedInterviewList[index]);
                }
              }
            }
          })

        });
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    resetCourseDesign(){
      this.courseDesignList = [];
      let newCourseDesignList = JSON.parse(JSON.stringify(this.bakCourseDesignList));
      for (let i = 0; i < newCourseDesignList.length; i++) {
        let temp = newCourseDesignList[i];
        this.$set(this.courseDesignList, i, temp);
      }
    },
    downward(i){
      let temp = this.courseDesignList[i+1];
      this.$set(this.courseDesignList, i + 1, this.courseDesignList[i])
      this.$set(this.courseDesignList, i, temp)
    },
    upward(i){
      let temp = this.courseDesignList[i-1];
      this.$set(this.courseDesignList, i - 1, this.courseDesignList[i])
      this.$set(this.courseDesignList, i, temp)
    },
    batchAddCourseDesign(){
      if (!this.num || this.num == 0) {
        this.$modal.msgError("天数必须大于0");
        return;
      }
      for (let i = 0; i < this.num; i++) {
        this.addCourseDesign(this.courseDesignList.length);
      }
      this.initDrag();
    },
    subCourseDesign(i){
      this.courseDesignList.splice(i, 1);
      this.initDrag();
    },
    addCourseDesign(i){
      //修改标题为新增
      this.title = "新增课程设计";
      let courseDesign = {
        "courseContent":"",
        "day":i+1,
        "stage":this.form.stage,
        "remarks":""
      }
      //this.courseDesignList.push(courseDesign);
      this.courseDesignList.splice(i+1, 0, courseDesign);
      this.initDrag(i+1);
    },
    /** 查询课程设计列表 */
    getList() {
      this.loading = true;
      listCourse_design(this.queryParams).then(response => {
        this.designList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        stage: null,
        days: 40
      };
      this.resetForm("form");
      this.bakCourseDesignList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课程设计";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const stageId = row.value
      getCourse_design(stageId).then(response => {
        this.form.stage=stageId;
        this.courseDesignList = response.data;
        if (this.courseDesignList.length === 0) {
          this.addCourseDesign()
        }
        else{
          this.title = "修改课程设计";
        }
        this.open = true;
        this.bakCourseDesignList = JSON.parse(JSON.stringify(this.courseDesignList));
        this.initDrag();
      });
    },
    onDragstart(event){
      // 设置数据传输并将当前拖动的元素的ID传递给数据
      let index = event.target.value.split('-')[1];
      this.dragItem = document.getElementById(index);
      if (this.dragItem == null || this.dragItem.id == null) {
        this.$modal.msgWarning("重新选择拖动元素");
        return;
      }
      event.dataTransfer.setData('text/plain', this.dragItem.id);
    },
    onDragover(event){
      // 防止默认操作
      event.preventDefault();
      // 检查拖动的元素是否超出了允许的位置
      if (event.currentTarget == null) {
        return;
      }
      if (event.currentTarget.id == null) {
        return;
      }
      if (this.dragItem == null) {
        return;
      }
      //isSameIndex
      if (this.dragItem.id == event.currentTarget.id) {
        event.dataTransfer.dropEffect = 'none';
      } else {
        event.dataTransfer.dropEffect = 'move';
      }
    },
    onDragenter(event){
      // 防止默认操作
      event.preventDefault();
    },
    onDragleave(event){
    },
    onDrop(event){
      // 拖动元素下标
      const currentIndex = event.dataTransfer.getData('text/plain');
      // 目标元素下标
      const targetIndex = parseInt(event.currentTarget.id);
      // 交换拖动元素和放置目标的位置
      // const temp = this.courseDesignList[dragIndex];
      // this.$set(this.courseDesignList, dragIndex, this.courseDesignList[dropIndex])
      // this.$set(this.courseDesignList, dropIndex, temp)

      //delete and get currentElement in a array
      let delArray = this.courseDesignList.splice(currentIndex,1);
      this.courseDesignList.splice(targetIndex,0,delArray[0]);
    },
    onDragend(event){
    },
    //初始化新增表单项拖动功能
    initDrag(){
      let vm = this;
      // 在下一个 DOM 更新周期中调用方法
      vm.$nextTick(() => {
        // 获取所有的 itemRefs 引用
        // const itemRefs = this.$refs.itemRefs;
        const itemRefs = document.querySelectorAll('.dragClass');
        itemRefs.forEach(item=>{
          item.removeEventListener('dragstart', vm.onDragstart);
          item.removeEventListener('dragover', vm.onDragover);
          item.removeEventListener('dragenter', vm.onDragenter);
          item.removeEventListener('dragleave', vm.onDragleave);
          item.removeEventListener('drop', vm.onDrop);

          item.addEventListener('dragstart', vm.onDragstart);
          item.addEventListener('dragover', vm.onDragover);
          item.addEventListener('dragenter', vm.onDragenter);
          item.addEventListener('dragleave', vm.onDragleave);
          item.addEventListener('drop', vm.onDrop);
        })
      });
    },
    /** 提交按钮 */
    submitForm() {
      //重新计算day数
      if (this.courseDesignList) {
        for (let i = 0; i < this.courseDesignList.length; i++) {
          let cd = this.courseDesignList[i];
          if (!cd.courseContent) {
            this.$modal.msgError("课程内容不能为空")
            return ;
          }
          cd.day = i+1;
        }
        updateCourse_design(this.form.stage,this.courseDesignList).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      }else{
        this.$modal.msgWarning("至少有一个课程设计")
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除课程设计编号为"' + ids + '"的数据项？').then(function() {
        return delCourse_design(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('teaching/design/export', {
        ...this.queryParams
      }, `design_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
